﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
using System.Windows.Threading;
using Microsoft.Phone.Tasks;
using Chrysalis.Services;

namespace Chrysalis.Internal
{
    public class ChooserExecutionContext<T> : IChooserExecutionContext where T : TaskEventArgs
    {
        // *** Fields ***

        private bool isActive = true;
        private T result;

        // *** Constructors ***

        public ChooserExecutionContext()
        {
        }

        // *** Properties ***

        public string CallbackMethod
        {
            get;
            set;
        }

        public string ChooserTypeName
        {
            get;
            set;
        }

        public bool IsActive
        {
            get
            {
                return isActive;
            }
        }

        // *** Methods ***

        public void Attach()
        {
            // Create a new instance of the required chooser

            Type chooserType = Type.GetType(ChooserTypeName);
            ChooserBase<T> chooser = Activator.CreateInstance(chooserType) as ChooserBase<T>;

            // Attach to the Completed event

            chooser.Completed += new EventHandler<T>(Chooser_Completed);
        }

        public void Chooser_Completed(object sender, T result)
        {
            // The chooser has now completed so we can deactivate this context so it is not reused

            isActive = false;

            // Call the callback on the current view model
            // NB: We wait first for the view model to be fully initialized

            this.result = result;
            ChrysalisService.Current.ViewModelInitialized += OnViewModelInitialized;
        }

        // *** Private Methods ***

        private void OnViewModelInitialized(object sender, ViewModelEventArgs e)
        {
            // Call the callback on the current view model

            object callbackTarget = e.ViewModel;
            MethodInfo methodInfo = callbackTarget.GetType().GetMethod(CallbackMethod);
            methodInfo.Invoke(callbackTarget, new object[] { result });

            // Unsubscribe from this event (we only need to do this once!)

            ChrysalisService.Current.ViewModelInitialized -= OnViewModelInitialized;
        }
    }
}
